<?php

namespace App\Http\Controllers\Mini;


use App\Models\ElectricMeterReadingLog;
use App\Models\ElectricPaymentOrder;
use App\Services\PropertyService;
use App\Models\ElectricChargingScheme;
use App\Models\Users;
use Illuminate\Support\Facades\DB;

/**
 * Class  Property
 * @package app\api\controller
 */
class PropertyController extends BaseController
{
    protected $redis = null;
    protected $ownerId = null;

    public function __construct()
    {
        DB::connection('mysql_center')->enableQueryLog();
        $this->ownerId = 157;
//        $this->ownerId=auth("user")->id();
    }


    /**
     * 2021/3/20--11:20
     * @effect:获取收费方案1,电费，2,水费，3，物业费
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:getPropertyPlanApi
     */
    public function getPropertyPlanApi(): array
    {
        $get = request()->all();
        $field_str = "electric_plan_id,water_plan_id,property_plan_id";
        $user = Users::select(Db::raw($field_str))->find($this->ownerId);
        if (empty($user)) {
            $this->error(['code' => 2, 'msg' => '请先登录']);
        }
        $plan_type = $get['plan_type'];
        $plan_type_str = '';
        switch ($plan_type) {
            case 1:
                $plan_type_str = 'electric';//电费
                break;
            case 2:
                $plan_type_str = 'water';//水费
                break;
            case 3:
                $plan_type_str = 'property';//物业费
                break;
        }
        $str = $plan_type_str . "_plan_id";
        if ($user[$str] == '') {
            return $this->error('您未设置方案，请联系平台');
        }
        $where = ['id' => $user[$str], 'fee_type' => $plan_type];
        $one_plan = ElectricChargingScheme::getSchemeByWhere($where);
        return $one_plan ? $this->success($one_plan, "获取缴费计划成功") : $this->error("暂无数据");
    }

    /**
     * 2021/3/20--11:20
     * @effect:物业费缴费详细页面
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:showPropertyApi
     */
    public function showPropertyApi(): array
    {
        $get = request()->all();
        $user_fields = 'id,province,city,area,room_number,community,community_area,property_plan_id,housing_area,last_payment_time,property_bill_balance';
        $one_user = Users::selectRaw(Db::raw($user_fields))->find($this->ownerId)->toArray();
        if (empty($one_user)) {
            $this->error('请先登录');
        }
        $str = "property_plan";
        $fields2 = 'id,unit_price,charging_months';
        $plan = $this->getPlanDetail($one_user, $str, $fields2);
        if (empty($plan)) {
            $this->error('未设置方案');
        }
        $address_arr = PropertyService::getAddressArr($one_user);
        extract($address_arr, null);
        /**
         * @var $address |省市区
         * @var $community_name |小区名称
         * @var $community_area_name |小区分区名称
         * @var $room_number |房间号
         */
        $property_service = new PropertyService();
        $cost_arr = $property_service->getCostArr($one_user, $plan);
        extract($cost_arr, null);
        /**
         * @var $one_price |单月物业费
         * @var $year_total |全年需缴纳物业费
         * @var  $last_month |最后缴纳记录
         * @var $now_balance |物业费余额
         * @var $arr1 |已缴纳月份
         */
        $data = [
            'plan' => $plan,//缴费计划
            'one_price' => $one_price,
            'year_total' => $year_total,//全年须缴纳费用
            'now_balance' => $one_user['property_bill_balance'],//当前余额
            'address' => $address,//地址
            'community_name' => $community_name,//小区名称
            'community_area_name' => $community_area_name,//小区分区名称
            'room_id' => $room_number,//房间号
            'last_month' => date('Y') . "." . $last_month,//缴纳物业费至
            'housing_area' => $one_user['housing_area']//住内面积
        ];
        return $this->success('返回成功', $data);
    }

    /**
     * 2021/3/20--11:22
     * @effect:物业费结算[]
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:settlementPropertyApi
     */
    public function settlementPropertyApi()
    {
        $get = request()->all();
        $flag = request('flag', 1);
        if ($flag == '') {
            $this->error('请传递缴费类型');
        }
        $str1 = 'property_plan_id,property_bill_balance,housing_area,id';
        $user = Users::select(Db::raw($str1))->find($this->ownerId);
        $arr = [];
        $this_month = (int)date('m');
        $plan = ElectricChargingScheme::select(Db::raw('unit_price,charging_months'))->find($user['property_plan_id']);

        if (empty($user)) {
            $this->error(['code' => 2, 'msg' => '请先登录']);
        }
        $months = [];
        $one_price = bcmul($user['housing_area'], $plan['unit_price'], 2);
        switch ($flag) {
            case 1://待缴费用，欠费
                if ($user['property_bill_balance'] >= 0) {//欠费状态
                    $months = [];
                } else {
                    [$arrears, $months, $billed_arr, $paid_month, $unpaid_arr] = (new PropertyService())->get_property_need($user, $plan, $one_price);
                }
                break;
            case 2://预交费
                if ($months == '') {
                    return $this->error('请传递缴费月份');
                }
//                if (isset($user['property_bill_balance']) && $user['property_bill_balance'] < 0) {
//                    return $this->error('请您先补齐欠费');
//                }

//大于或等于零
                $str = $get['months'];
                $months = explode(',', $str);//
                break;
        }
        $m_count = count($months);

        $need = bcmul($one_price, $m_count, 2);
        $money = $need;
        $data = [
            'money' => $money,//缴费金额
            'months' => $months,//缴费月份
            'need' => $need,//代缴纳费用
        ];
        return $this->success($data, "物业费计算成功");
    }

    /**
     * 显示物业费缴纳详细
     * @author Sdd
     */
    public function showSettlementDetailsApi()
    {
        $str1 = "property_bill_balance,id,property_plan_id,last_payment_time,province,city,area,community,community_area,room_number,housing_area";
        $property_server = new PropertyService();
        $user = Users::select(DB::raw($str1))->find($this->ownerId)->toArray();
        if (empty($user)) {
            return $this->error(['code' => 2, 'msg' => '请先登录']);
        }
        if (empty($user['property_plan_id'])) {
            return $this->error('您尚未匹配物业缴费方案，请联系管理员');
        }
        $str = "property_plan_id";

        $plan = ElectricChargingScheme::getSchemeByWhere(['id' => $user[$str]]);//物业缴费方案

        if (empty($plan)) {
            return $this->error('您尚未匹配物业缴费方案，请联系管理员');
        }
        $cost_arr = $property_server->getCostArr($user, $plan);//获取地址数组
        extract($cost_arr, null);
        /**
         * @var $one_price |单月物业费
         * @var $year_total |全年需缴纳物业费
         * @var  $last_month |最后缴纳记录
         * @var$cumulativeConsumption |累计缴纳费用
         * @var $billed_arr |缴纳明细数组，用于显示列表
         * @var $unpaid_arr |未出帐订单
         * @var $arr1 |已缴纳月份
         * @var $arrears |需缴纳费用
         */
        $address_arr = PropertyService::getAddressArr($user);
        extract($address_arr, null);
        /**
         * @var $address |省市区
         * @var $community_name |小区名称
         * @var $community_area_name |小区分区名称
         * @var $room_number |房间号
         */
        //结算时间
        $time = ElectricMeterReadingLog::where(['user_id' => $this->ownerId, 'type' => 3])
            ->orderByDesc('month_time')
            ->value('month_time');

        $data = [
            'room' => $user['housing_area'],//房间面积
            'year_total' => $year_total,//年度物业费
            'last_month' => $last_month,//上一次缴纳时间
            'now_balance' => $user['property_bill_balance'],
            'address' => $address,//地址
            'community_name' => $community_name,//小区
            'community_area_name' => $community_area_name,//小区分区
            'room_id' => $room_number,//房间号
            'arr' => $arr1,//累计缴纳费用
            'cumulativeConsumption' => $cumulativeConsumption,//累计缴纳费用
            'billed_arr' => $billed_arr,//缴纳明细数组，用于显示列表
            'unpaid_arr' => $unpaid_arr,//未出帐订单
            'pending' => $arrears,//代缴纳
            'settlement_time' => $time ? date('Y-m', $time) : '---',//最后结算时间
            'unpaid_money' => array_sum(array_column($unpaid_arr, "one_price")),
            'billed_money' => array_sum(array_column($billed_arr, "one_price"))
        ];
        return $this->success($data, "获取成功");
    }

    /**
     * 2021/3/20--15:26
     * @effect:
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:monthRadioCheckedApi
     */
    public function monthRadioCheckedApi()
    {
        $property_service = new PropertyService();
        $get = request()->all();
//        $ownerId = auth("user")->id();
        $one_user = Users::find($this->ownerId);
        if (empty($one_user)) {
            $this->error('请先登录');
        }
        $str = "property_plan_id";

        $plan = ElectricChargingScheme::select(DB::raw("charging_months,unit_price"))->find($one_user[$str]);
        $charging_months = explode(',', $plan['charging_months']);
        $one_price = bcmul($plan['unit_price'], $one_user['housing_area'], 2);
        foreach ($charging_months as $k1 => $v1) {
            $month_arr = [
                "date" => date('Y') . '.' . str_pad($v1, 2, 0, STR_PAD_LEFT),
                "month" => $v1,
            ];
//            $months[] = date('Y') . '.' . str_pad($v1, 2, 0, STR_PAD_LEFT);
            $months[] = $month_arr;
        }
        $arr1 = ElectricPaymentOrder::getPaidMonths($one_user);
        if (empty($arr1)) {
            if (isset($user['last_payment_time']) && $user['last_payment_time'] != '') {
                $now_month = (int)date('m', $user['last_payment_time']);
                for ($i = 1; $i <= $now_month; $i++) {
                    $arr1[] = date('Y') . '.' . str_pad($i, 2, 0, STR_PAD_LEFT);
                }
            } else {
                $arr1 = [];
            }

        }
        $month_data = [];
        foreach ($months as $k => $v) {
            if (in_array($v['date'], $arr1) || in_array($v['date'], ["2021.01", "2021.02", "2021.03"])) {
                $checked = 1;
            } else {
                $checked = 0;
            }

            $month_data[] = [
                'index'=>$k+1,
                'month' => $v['date'],
                'checked' => $checked
            ];
        }

        return $this->success(compact("month_data", "one_price"), '返回成功');

    }

    /**
     * 2021/3/22--14:47
     * @effect:消费账单
     * @return array
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:property_log
     */
    public function property_log(): array
    {
        $log = [];
        $total = 0;
        $type = request()->get("type") ?: "3";
        $log_db = ElectricMeterReadingLog::selectRaw("day_cost,user_id,create_time")->where(["user_id" => $this->ownerId, "type" => $type]);
        if (request()->get("date")) {
            $date_arr = explode(".", request()->get("date"));
            $log_db->where(["year" => request()->get($date_arr[0]), "month" => $date_arr[1]]);
        }
        $log_db = $log_db->get();
        if ($log_db->count()) {
            $log = $log_db->each(function ($item) {
                $item['username'] = $item->one_user->username;
                return $item;

            })->toArray();
            $total = array_sum(array_column($log, 'day_cost'));
        }
        return $this->success(compact("log", "total"), "获取成功");
    }

    /**
     * 月初扣电费
     * @return array|Json|void
     * @author sdd
     */
    public function settlementProperty()
    {
        $this->owner_insert_dui();
        $redis = $this->redis;
        $data = [];
        $key = 'property_plan';
        while (true) {
            try {
                $value = $redis->RPOP($key);
                if (!$value) {
                    break;
                }
                /*
                * 利用$value进行逻辑和数据处理
                */
                $ownerInfo = json_decode($value, 1);
                //计算物业费
                $price = bcmul($ownerInfo['housing_area'], $ownerInfo['price'], 2);
                $balance = bcsub($ownerInfo['property_bill_balance'], $price, 2);
                $res = Db::name('electric_platform_owner')->where(['id' => $ownerInfo['id']])
                    ->update(['property_bill_balance' => $balance]);

                //数据库插入数据失败,回滚
                if (!$res) {
                    $redis->LPush($key, $value);
                } else {
                    //插入
//                    $order_arr = [
//                        'user_id' => $ownerInfo['id'],//业主id
//                        //'username' => $ownerInfo['username'],//业主姓名
//                        'feeType' => 3,//费用类型
//                        'type' => 3,//缴费类型
//                        'paymentMoney' => $price,//支付金额
//                        'pay_type' => 3,//支付方式
//                        'orderNo' => Data::uniqidNumberCode(12),//订单号
//                        'year' => date('Y'),
//                        'month' => date('m'),
//                        'day' => date('d'),
////                        'split_money' => $split_money//分账金额
//                        'status' => 2
//                    ];

                    $logData = [];
                    $logData['owner_id'] = $ownerInfo['id'];
                    $logData['before_balance'] = $ownerInfo['property_bill_balance'];
                    $logData['after_balance'] = $balance;
                    $logData['bill_balance'] = $price;
                    $logData['pay_type'] = 4; //扣费
                    $logData['type'] = 3;  //物业费

//                    Db::name('electric_payment_order')->insertGetId($order_arr);

                    Db::name('electric_fee_log')->insert($logData);
                }
                //把物业费记录插入到队列中
                $insertData['user_id'] = $ownerInfo['id'];
                //$insertData['username'] = $ownerInfo['username'];
                //$insertData['mobile'] = $ownerInfo['mobile'];
                // $insertData['room_number'] = $ownerInfo['room_number'];
                $insertData['community_id'] = $ownerInfo['community_id'];
                $insertData['year'] = date('Y', strtotime('-1 days'));
                $insertData['month'] = date('m', strtotime('-1 days'));
                $insertData['day_cost'] = $price;
                $insertData['month_time'] = strtotime(date('Y-m', strtotime('-1 days')));
                $redis->LPush('property', json_encode($insertData));

            } catch (\Exception $e) {
                echo $e->getMessage();
            }
        }
        echo '222';
    }

    /**
     * 处理物业费log表的数据
     * @return array|Json|void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author ypp
     */
    public function addProperty()
    {
        $redis = $this->redis;
        $key = 'property';
        while (true) {
            try {
                $value = $redis->RPOP($key);
                if (!$value) {
                    break;
                }
                /*
                * 利用$value进行逻辑和数据处理
                */
                $data = json_decode($value, 1);
                $data['type'] = 3;
                $res = Db::name('electric_meter_reading_log')->insert($data);
                //数据库插入数据失败,回滚
                if (!$res) {
                    $redis->LPush($key, $value);
                }
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
        //echo $res;
    }

    /**
     * 将用户表的数据插入到redis中
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function owner_insert_dui()
    {
        //查询当前月份需要交物业费的业主数据
        $monthtime = strtotime(date('Y-m', time()));
        $data = Db::name('electric_platform_owner')
            ->field('id,username,mobile,room_number,community,property_plan_id,housing_area,property_bill_balance')
            ->where('last_payment_time', 'lt', $monthtime)
            ->select();
        //查询所有的物业费
        $fee = Db::name('electric_charging_scheme')->where(['fee_type' => 3])->column('id,unit_price');
        $redis = $this->redis;
        $redis->del('property_plan');
        foreach ($data as $k => $v) {
            $addData['id'] = $v['id'];
            $addData['username'] = $v['username'];
            $addData['mobile'] = $v['mobile'];
            $addData['room_number'] = $v['room_number'];
            $addData['community_id'] = $v['community'];
            $addData['property_plan_id'] = $v['property_plan_id'];
            $unit_price = isset($fee[$v['property_plan_id']]) ? $fee[$v['property_plan_id']] : '';
            $addData['price'] = $unit_price;
            $addData['housing_area'] = $v['housing_area'];
            $addData['property_bill_balance'] = $v['property_bill_balance'];
            //只有添加收费方案的业主才放入redis中
            if (!empty($unit_price)) {
                $redis->LPush('property_plan', json_encode($addData));
            }
        }
    }

    /**
     * 获取计划详情
     * @param $one_user
     * @param string $str
     * @param string $fields2
     */
    public function getPlanDetail($one_user, string $str, string $fields2)
    {

        $plan = ElectricChargingScheme::getSchemeByWhere(['id' => $one_user[$str . "_id"], 'status' => 1], $fields2);//物业缴费方案
        return $plan;
    }

}
